package com.example.canalclientsync.canal.service.impl;

import com.example.canalclientsync.canal.service.DirService;
import com.example.canalclientsync.canal.mapper.db1.DirMapper;
import com.example.canalclientsync.canal.po.Dir;
import com.example.canalclientsync.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;

/**
 * @author chen.cr
 * @since 2023/9/15
 */
@Service
@Slf4j
public class DirServiceImpl implements DirService {

    @Resource
    private DirMapper dirMapper;

    @Override
    public Integer searchProjectIdByDir(Dir dir) {
        String treeId = dir.getTreeId();
        String[] split = treeId.replaceFirst("/", "").split("/");
        if (split.length < 2) {
            return null;
        }
        long projectDirId = Long.parseLong(split[1]);

        Dir projectDir = dirMapper.findByDirIdAndTenantId(projectDirId, dir.getTenantId());
        Assert.isTrue(projectDir.getType() == CommonUtils.PROJECT_DIR_TYPE, "查询项目文件夹异常[类型不匹配]");
        Assert.notNull(projectDir.getTypeRelateId(), "查询项目文件夹异常[type_relate_id为空]");

        return Integer.parseInt(projectDir.getTypeRelateId());
    }

    @Override
    public Integer searchUserIdByDir(Dir dir) {
        String treeId = dir.getTreeId();
        String[] split = treeId.replaceFirst("/", "").split("/");
        long personalDirId = Long.parseLong(split[0]);

        Dir personalDir = dirMapper.findByDirIdAndTenantId(personalDirId, dir.getTenantId());
        Assert.isTrue(personalDir.getType() == CommonUtils.PERSONAL_SPACE_DIR_TYPE, "查询个人空间文件夹异常[类型不匹配]");
        Assert.notNull(personalDir.getTypeRelateId(), "查询个人空间文件夹异常[type_relate_id为空]");

        return Integer.parseInt(personalDir.getTypeRelateId());
    }

    @Override
    public Integer searchLeafDepartmentIdByDir(Dir dir) {
        Long leafDepartmentDirId = CommonUtils.getLeafDepartmentDirIdFormDir(dir);
        Dir leafDepartmentDir = dirMapper.findByDirIdAndTenantId(leafDepartmentDirId, dir.getTenantId());
        Assert.isTrue(leafDepartmentDir.getType() == CommonUtils.DEPARTMENT_DIR_TYPE, "查询部门文件夹异常[类型不匹配]");
        Assert.notNull(leafDepartmentDir.getTypeRelateId(), "查询部门文件夹异常[type_relate_id为空]");

        return Integer.parseInt(leafDepartmentDir.getTypeRelateId());
    }

    @Override
    public Dir searchLeafCatalogDirByDir(Dir dir) {
        Long leafCatalogDirId = CommonUtils.getLeafProjectCatalogDirIdFormDir(dir);
        Dir leafCatalogDir = dirMapper.findByDirIdAndTenantId(leafCatalogDirId, dir.getTenantId());
        Assert.isTrue(leafCatalogDir.getType() == CommonUtils.PROJECT_CATALOG_DIR_TYPE, "查询项目目录文件夹异常[类型不匹配]");
        return leafCatalogDir;
    }


}
